package com.imy.lua.lib.thread;

import android.content.Context;
import android.os.Looper;
import android.util.Log;

import androidx.annotation.NonNull;

import com.immomo.mls.LuaViewManager;
import com.immomo.mls.annotation.LuaBridge;
import com.immomo.mls.annotation.LuaClass;
import com.immomo.mls.utils.LVCallback;
import com.immomo.mls.wrapper.Translator;
import com.immomo.mls.wrapper.callback.IVoidCallback;
import com.imy.common.util.ALog;
import com.imy.lua.manger.thread.ThreadManger;

import org.luaj.vm2.Globals;
import org.luaj.vm2.LuaValue;

/**
 * Created by MLN Template 注册方法: Register.newUDHolderWithLuaClass(UDThread.LUA_CLASS_NAME, UDThread.class, true) 若想在Java层实现参数自动转换，则增加注册:
 *
 * @see com.immomo.mls.MLSBuilder#registerCovert
 * @see com.immomo.mls.MLSBuilder.CHolder new MLSBuilder.CHolder(UDThread.class)
 *
 * 一个应用只存在一个脚本线程
 */
@LuaClass
public class UDScriptThread {
  /**
   * Lua类型，Lua可由此创建对象: local obj = Thread()
   */
  public static final String LUA_CLASS_NAME = "ScriptThread";

  private LVCallback mCallBack;

  /**
   * Lua构造函数
   *
   * @param g    虚拟机
   * @param init 构造方法中传入的参数
   */
  public UDScriptThread(@NonNull Globals g, @NonNull LuaValue[] init) {
    if (init.length > 0) {
      if (init[0].isNil() || !init[0].isFunction()) {
        ALog.e("Thread 对象 传入的参数不能为空 并且必须为function");
        return;
      }
      mCallBack = Translator.translateLuaToJava(init[0], LVCallback.class);
    }
  }

  private Runnable mRunnable = new Runnable() {
    @Override
    public void run() {
      ALog.i("Thread 开始运行" + "当前线程:" + String.valueOf(Thread.currentThread())
          + "主线程" + Looper.getMainLooper().getThread());
      mCallBack.call();
    }
  };

  @LuaBridge
  public void stop() {
    android.os.Process.killProcess(android.os.Process.myPid());
  }

  @LuaBridge
  public void start() {
    //一个
    ThreadManger.setScriptFlag(true);
    ThreadManger.getScriptThread().execute(mRunnable);
    //添加一个标记

  }
  //<editor-fold desc="Bridge API">

  /**
   * 获取上下文，一般情况，此上下文为Activity
   *
   * @param globals 虚拟机，可通过构造函数存储
   */
  protected Context getContext(@NonNull Globals globals) {
    LuaViewManager m = (LuaViewManager) globals.getJavaUserdata();
    return m != null ? m.context : null;
  }

}
